package vpfarm.gui;

import java.awt.BorderLayout;
import java.io.IOException;
import java.net.UnknownHostException;

import javax.swing.JFrame;

import jtools.ai.agenten.AMessage;
import jtools.ai.agenten.Agent;
import jtools.ai.agenten.CycleBehavior;
import jtools.network.mqueue.Adress;
import jtools.network.mqueue.MessageException;
import vpfarm.Constants;
import vpfarm.data.Status;

public class StatusAgent extends Agent {

	
	public static void main(String[] arg){
		try {
//			Master.main(arg);
			new StatusAgent(new Adress("localhost", 2000), null, 15*1000);
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MessageException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static void start(String h, int p){
		try {
			new StatusAgent(new Adress(h,p), null, 10*1000);
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MessageException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	StatusPanel panel = null;
	long refresh = 15*1000;
	private JFrame frame;
	public StatusAgent(Adress adr, StatusPanel p, long re) throws IOException, MessageException {
		super(adr);

		this.refresh = re;
	}
	public void onEnd(){
		this.frame.dispose();
	}
	public void onStart(){
		this.panel = new StatusPanel();
		this.panel.setAgent(this);
		this.frame = new JFrame();
		frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		frame.setLayout(new BorderLayout());
		frame.add(this.panel, BorderLayout.CENTER);
		frame.pack();
		frame.setVisible(true);
		
		new Thread(new Runnable(){
			public void run(){
				while(isAlive()){
					AMessage msg = new AMessage(Constants.ASK_FOR_STATUS);
					msg.addReciver(Constants.MASTER_NAME);
					sendMessage(msg);
					try {
						Thread.sleep(refresh);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}).start();
		addBehavior(new CycleBehavior(){

			@Override
			public void execute() {
				AMessage msg = reciveMessage(true);
				if (msg.getSubject() == Constants.SEND_STATUS){
					Status status = (Status) msg.getContent();
					try {
						panel.setStatus(status);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}else
					pushBack(msg);
			}

			@Override
			public void onEnd() {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				
			}
			
		});
	}

	public void updateNow() {
		AMessage msg = new AMessage(Constants.ASK_FOR_STATUS);
		msg.addReciver(Constants.MASTER_NAME);
		sendMessage(msg);
	}

}
